package com.scorpio.goods.service.impl;

import java.util.Arrays;
import java.util.List;

import com.scorpio.common.exception.CustomException;
import org.springframework.stereotype.Service;
import com.scorpio.goods.mapper.GoodsCategoryMapper;
import com.scorpio.goods.domain.GoodsCategoryEntity;
import com.scorpio.goods.service.IGoodsCategoryService;
import com.scorpio.common.service.impl.BaseServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品类目Service业务层处理
 *
 * @author scorpio
 * @date 2021-11-03
 */
@Service
public class GoodsCategoryServiceImpl extends BaseServiceImpl<GoodsCategoryMapper, GoodsCategoryEntity> implements IGoodsCategoryService {

    //查询
    @Override
    public GoodsCategoryEntity selectById(Long id) {
        return baseDao.selectById(id);
    }

    //查询列表
    @Override
    public List<GoodsCategoryEntity> selectList(GoodsCategoryEntity entity) {
        return baseDao.list(entity);
    }

    //新增$
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(GoodsCategoryEntity entity) {
        check(entity);
        return baseDao.insert(entity);
    }


    //修改$
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(GoodsCategoryEntity entity) {
        if (entity.getId().equals(entity.getPid())) {
            throw new CustomException("无法选择自己为上级");
        }
        check(entity);
        return baseDao.updateById(entity);
    }

    private void check(GoodsCategoryEntity entity) {
        if (entity.getPid() == 0 || entity.getPid() == null) {
            entity.setLevel(1);
        } else {
            GoodsCategoryEntity pItem = baseDao.selectById(entity.getPid());
            if (pItem.getLevel() != 1) {
                throw new CustomException("只能创建二级目录");
            }
            entity.setLevel(2);
        }
    }

    //批量删除$
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteByIds(Long[] ids) {
        for (Long id : ids) {
            if (baseDao.countByParent(id) > 0) {
                throw new CustomException("请先删除分类下级");
            }
        }
        return baseDao.updateDelete(ids);
    }
}
